$(function() {
	// 页面控件
	var $dataTable = $('#dataTable'); // 表格
	var $dataTableToolbar = $('#dataTableToolbar'); // 表格：工具栏
	//var $btnAddToggle = $('#btnAddToggle'); // 表格：添加按钮
	var $btnEditToggle = $('#btnEditToggle'); // 表格：修改按钮
	//var $btnRemoveToggle = $('#btnRemoveToggle'); // 表格：删除按钮
	//var $btnCheckAll = $('#btnCheckAll'); // 表格：全选按钮
	//var $btnInvertCheck = $('#btnInvertCheck'); // 表格：反选按钮
	//var $btnUncheckAll = $('#btnUncheckAll'); // 表格：取消选择按钮
	
	var $editDialog = $('#editDialog'); // 添加/修改窗口
	var $editDialogLabel = $('#editDialogLabel'); // 添加/修改窗口：标题
	var $editForm = $('#editForm'); // 添加/修改窗口：表单
	var $displayName = $('#displayName'); // 添加/修改窗口：名称
//	var $displayPort = $('#displayPort'); // 添加/修改窗口：端口
	var $hashTheo = $('#hashTheo'); // 添加/修改窗口：理论算力
	var $hashPass = $('#hashPass'); // 添加/修改窗口：达标算力
	var $hashPassRateSlider = $('#hashPassRateSlider'); // 添加/修改窗口：算力达标比率滑块
	var $hashPassRate = $('#hashPassRate'); // 添加/修改窗口：算力达标比率
	var $btnSave = $('#btnSave'); // 添加/修改窗口：保存按钮
	var $btnReset = $('#btnReset'); // 添加/修改窗口：重置按钮
	
	initWidgets();
	initListeners();
	initValidators();
	
	var formData; // 表单数据
	var saveMode = 0; // 保存方式：1：添加；2：修改
	
	// 弹出添加窗口时使用的初始表单控件值
	var emptyData = {id:'', name:'', port:4028, power:0, hashTheo:0, hashPass:0, hashPassRate:0, fanNum:0, fanMaxSpeed:0, tempNum:0, tempMaxValue:0, chainMinNum:0, chipMinNum:0};
	
	// 弹出添加窗口
	function openAddDialog() {
		$editDialogLabel.text('添加矿机类型');
		initFormData(emptyData);
		$editDialog.modal('show');
		saveMode = 1;
	}
	
	// 弹出修改窗口
	function openEditDialog(data) {
		$editDialogLabel.text('修改矿机类型');
		initFormData(data);
		$editDialog.modal('show');
		saveMode = 2;
	}

	// 弹出删除确认窗口
	function openRemoveDialog(datas) {
		var tableDatas = $dataTable.bootstrapTable('getData');
		var title = '';
		if (datas.length == 1) {
			title = '将删除矿机类型' + datas[0].name + '。';
		} else if(datas.length == tableDatas.length) {
			title = '将删除所有矿机类型。';
		} else {
			title = '将删除所选' + datas.length + '个矿机类型。';
		}
		swal({
	        title: title,
	        text: '删除矿机类型可能会导致数据异常，请谨慎操作！',
	        type: "warning",
	        showCancelButton: true,
	        cancelButtonText : "让我再考虑一下…",
	        confirmButtonColor: "#ed5565",
	        confirmButtonText : "是的，我要删除！"
	    }, function(isConfirm) {
			if (isConfirm) {
				doDelete(JSON.stringify(datas));
			}
		});
	}

	// 初始化表单控件的值
	function initFormData(data) {
		formData = data;
		$.each(formData, function (key, value) {
			$('#' + key).val(value);
		});
		$displayName.text(data.name);
//		$displayPort.text(data.port);
		$hashPassRateSlider.data('ionRangeSlider').update({
			from: formData.hashPassRate
		});
		$hashPassRate.val(formData.hashPassRate);
		$editForm.validate().form();
	}

	// 重置表单
	function doReset() {
		initFormData(formData);
	}

	// 保存（修改或添加）
	function doSave() {
		var data = JSON.stringify($editForm.serializeObject());
		if (saveMode == 1) {
			doPost(data);
		} else if (saveMode == 2) {
			doPut(data);
		}
	}

	// 添加
	function doPost(data) {
		$.ajax({
			url: 'types',
			type: 'POST',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			data: data,
			success: function(result) {
				if (result.success) {
					toastr.success(result.message, '添加成功');
					$editDialog.modal('hide');
					$dataTable.bootstrapTable('refresh');
				} else {
					toastr.error(result.message, '添加失败');
				}
			},
			error: function(request, status, error) {
				toastr.error(error, '异常');
			}
		});
	}

	// 修改
	function doPut(data) {
		$.ajax({
			url: 'types',
			type: 'PUT',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			data: data,
			success: function(result) {
				if (result.success) {
					toastr.success(result.message, '修改成功');
					$editDialog.modal('hide');
				} else {
					toastr.error(result.message, '修改失败');
				}
				$dataTable.bootstrapTable('refresh');
			},
			error: function(request, status, error) {
				toastr.error(error, '异常');
				$dataTable.bootstrapTable('refresh');
			}
		});
	}

	// 删除
	function doDelete(data) {
		$.ajax({
			url: 'types',
			type: 'DELETE',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			data: data,
			success: function(result) {
				if (result.success) {
					toastr.success(result.message, '删除成功');
					$dataTable.bootstrapTable('refresh');
				} else {
					toastr.error(result.message, '删除失败');
				}
			},
			error: function(request, status, error) {
				toastr.error(error, '异常');
			}
		});
	}

	function getHeight() {
	    return $(window).height() - 40;
	}
	
	// 初始化表单验证
	function initValidators() {
		var validIcon = "<i class='fa fa-times-circle'></i> ";
		$editForm.validate({
			rules: {
				//name: { required: true, minlength: 2, maxlength: 10 },
				port: { required: true, digits: true, min: 1, max: 65535 },
				power: { required: true, number: true, min: 0.001 },
				hashTheo: { required: false, number: true, min: 0, max: 10000 },
				hashPass: { required: false, number:true, min: 0, max: 10000},
				hashPassRate: { required: false, digits: true, min: 0, max: 100 },
				fanNum: { required: false, digits: true, min: 0, max: 100 },
				fanMaxSpeed: { required: false, digits: true, min: 0, max: 10000 },
				tempNum: { required: false, digits: true, min: 0, max: 100 },
				tempMaxValue: { required: false, digits: true, min: 0, max: 100 },
				chainMinNum: { required: false, digits: true, min: 0, max: 100 },
				chipMinNum: { required: false, digits: true, min: 0, max: 1000 }
			},
			messages: {
				//name: validIcon + '矿机类型名称须为2-10个字符。',
				port: validIcon + '矿机端口号须为1-65535的整数。',
				power: validIcon + '无效的单机功耗。',
				hashTheo: validIcon + '无效的理论算力（0-10000）。',
				hashPass: validIcon + '无效的达标算力（0-10000）。',
				hashPassRate: validIcon + '无效的算力达标比率（0-100）。',
				fanNum: validIcon + '无效的风扇数（0-100）。',
				fanMaxSpeed: validIcon + '无效的风扇最大转速（0-10000）。',
				tempNum: validIcon + '无效的温感数（0-100）。',
				tempMaxValue: validIcon + '无效的最高温度（0-100）。',
				chainMinNum: validIcon + '无效的最少工作链条数（0-100）。',
				chipMinNum: validIcon + '无效的最少工作芯片数（0-1000）。'
			}
		});
	}
	
	// 初始化事件监听
	function initListeners() {
		$(window).resize(function () {
			$dataTable.bootstrapTable('resetView', {
	            height: getHeight()
	        });
	    });
		
		$hashTheo.on('change', function() {
			var theo = $hashTheo.val();
			if (!$.isNumeric(theo)) {
				theo = 0;
			}
			var pass = $hashPass.val();
			if (!$.isNumeric(pass)) {
				pass = 0;
			}
			pass = parseFloat(pass);
			theo = parseFloat(theo);
			if (pass > theo) {
				pass = theo;
				$hashPass.val(pass);
			}
			if (pass == 0 || theo == 0) {
				$hashPassRateSlider.data('ionRangeSlider').update({
		    		from: 0
		    	});
		    	$hashPassRate.val(0);
			} else {
				var rate = pass / theo * 100;
				$hashPassRateSlider.data('ionRangeSlider').update({
		    		from: Math.round(rate)
		    	});
		    	$hashPassRate.val(Math.round(rate));
			}
		});
		$hashPass.on('change', function() {
			var pass = $hashPass.val();
			if (!$.isNumeric(pass)) {
				pass = 0;
			}
			var theo = $hashTheo.val();
			if (!$.isNumeric(theo)) {
				theo = 0;
			}
			pass = parseFloat(pass);
			theo = parseFloat(theo);
			if (pass > theo) {
				pass = theo;
				$hashPass.val(pass);
			}
			if (pass == 0 || theo == 0) {
				$hashPassRateSlider.data('ionRangeSlider').update({
		    		from: 0
		    	});
		    	$hashPassRate.val(0);
			} else {
				var rate = pass / theo * 100.0;
				$hashPassRateSlider.data('ionRangeSlider').update({
		    		from: Math.round(rate)
		    	});
		    	$hashPassRate.val(Math.round(rate));
			}
		});
		// 添加/修改窗口：算力达标比率-值改变时更新滑块位置
	    $hashPassRate.on('change', function() {
	    	var value = $hashPassRate.val();
	    	if ($.isNumeric(value)) {
	    		if (value < 0) {
	    			value = 0;
	    		} else if (value > 100) {
	    			value = 100;
	    		}
	    	} else {
	    		value = 0;
	    	}
	    	$hashPassRateSlider.data('ionRangeSlider').update({
	    		from: value
	    	});
	    	$hashPassRate.val(value);
	    	var theo = $hashTheo.val();
	    	if (!$.isNumeric(theo)) {
	    		theo = 0;
	    	}
        	if (value == 0 || theo == 0) {
        		$hashPass.val(0);
        	} else {
        		var pass = theo * value / 100;
        		$hashPass.val(pass);
        	}
	    });
	    // 添加/修改窗口：保存按钮
		$btnSave.on('click', function() {
			var valid = $editForm.validate().form();
			if (!valid) {
				return;
			}
			doSave();
		});
		// 添加/修改窗口：重置按钮
		$btnReset.on('click', function() {
			doReset();
		});
		
		// 表格：添加按钮
		/*$btnAddToggle.on('click', function() {
			openAddDialog();
		});*/
	    // 表格：修改按钮
		$btnEditToggle.on('click', function() {
			var selections = $dataTable.bootstrapTable('getSelections');
			if (selections.length == 0) {
				toastr.warning('请选择一个要修改的矿机类型。', '提示');
				return;
			} else if (selections.length > 1) {
				toastr.warning('只能选择一个矿机类型进行修改。', '提示');
				return;
			}
			openEditDialog(selections[0]);
		});
		/*// 表格：删除按钮
		$btnRemoveToggle.on('click', function() {
			var selections = $dataTable.bootstrapTable('getSelections');
			if (selections.length == 0) {
				toastr.warning('请选择要删除的矿机类型。', '提示');
				return;
			}
			openRemoveDialog(selections);
		});
		// 表格：全选按钮
		$btnCheckAll.on('click', function() {
			$dataTable.bootstrapTable('checkAll');
		});
		// 表格：反选按钮
		$btnInvertCheck.on('click', function() {
			var datas = $dataTable.bootstrapTable('getData');
			for (var i=0; i<datas.length; i++) {
				if (datas[i].checkStatus) {
					$dataTable.bootstrapTable('uncheck', i);
				} else {
					$dataTable.bootstrapTable('check', i);
				}
			}
		});
		// 表格：取消选择按钮
		$btnUncheckAll.on('click', function() {
			$dataTable.bootstrapTable('uncheckAll');
		});*/
	}
	
	// 初始化页面控件
	function initWidgets() {
		// 添加/修改窗口：“算力达标比率”滑块
		$hashPassRateSlider.ionRangeSlider({
			type: "single",
			min: 0,
			max: 100,
			from: 0,
			step: 1,
			keyboard: true,
	        onChange: function (data) {
	        	var value = data.from;
	        	$hashPassRate.val(value);
	        	var theo = $hashTheo.val();
		    	if (!$.isNumeric(theo)) {
		    		theo = 0;
		    	}
	        	if (value == 0 || theo == 0) {
	        		$hashPass.val(0);
	        	} else {
	        		var pass = theo * value / 100;
	        		$hashPass.val(pass);
	        	}
	        }
	    });
		
		// 表格
		$dataTable.bootstrapTable({
			height: getHeight(),
			url: 'types',
			idField: 'id',
			search: true,
			//clickToSelect: true,
			pagination: false,
			sidePagination: 'server',
			showRefresh: true,
			showToggle: true,
			showColumns: true,
			toolbar: '#dataTableToolbar',
			iconSize: 'outline',
			icons: {
				paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
	            paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
	            refresh: 'glyphicon-repeat',
				toggle: 'glyphicon-list-alt',
				columns: 'glyphicon-list',
	            detailOpen: 'glyphicon-plus icon-plus',
	            detailClose: 'glyphicon-minus icon-minus'
			},
			editable: true,
			onEditableSave: function(field, row, oldValue, $el) {
				doPut(JSON.stringify(row));
			},
			columns: [
				{
					field: 'checkStatus',
					checkbox: true,
					align: 'center'
				},
				{
					field: 'id',
					title: 'ID',
					align: 'center',
					visible: false
				},
				{
					field: 'name',
					title: '类型名称',
					halign: 'center',
					align: 'left',
					sortable: true,
					sortName: 'name'/*,
					editable: {
						type: 'text',
						validate: function(value) {
							value = $.trim(value);
							if (!value || value.length < 2 || value.length > 10) {
								return '矿机类型名称必须为2-10个字符。';
							}
							return '';
						}
					}*/
				},
				{
					field: 'port',
					title: '端口',
					align: 'center',
					editable: {
						type: 'text',
						validate: function(value) {
							value = $.trim(value);
							var ex = /^\d+$/;
							if (!(ex.test(value)) || value < 1 || value > 65535) {
								return '矿机端口号必须为1-65535的整数。';
							}
							return '';
						}
					}
				},
				{
					field: 'power',
					title: '单机功耗(KW)',
					align: 'center',
					editable: {
						type: 'text',
						validate: function(value) {
							value = $.trim(value);
							if (!$.isNumeric(value) || value <= 0) {
								return '无效的单机功耗。';
							}
							return '';
						}
					}
				},
				{
					field: 'hashTheo',
					title: '理论算力',
					align: 'center',
					editable: {
						type: 'text',
						validate: function(value) {
							value = $.trim(value);
							if (!$.isNumeric(value) || value < 0 || value > 10000) {
								return '无效的理论算力（0-10000）。';
							}
							return '';
						}
					}
				},
				{
					field: 'hashPass',
					title: '达标算力',
					align: 'center',
					editable: {
						type: 'text',
						validate: function(value) {
							value = $.trim(value);
							if (!$.isNumeric(value) || value < 0 || value > 10000) {
								return '无效的达标算力（0-10000）。';
							}
							return '';
						}
					}
				},
				{
					field: 'hashPassRate',
					title: '算力达标比率（%）',
					align: 'center',
					editable: {
						type: 'text',
						validate: function(value) {
							value = $.trim(value);
							var ex = /^\d+$/;
							if (!ex.test(value) || value < 0 || value > 100) {
								return '无效的算力达标比率（0-100）。';
							}
							return '';
						}
					}
				},
				{
					field: 'fanNum',
					title: '风扇数',
					align: 'center',
					editable: {
						type: 'text',
						validate: function(value) {
							value = $.trim(value);
							var ex = /^\d+$/;
							if (!ex.test(value) || value < 0 || value > 100) {
								return '无效的风扇数（0-100）。';
							}
							return '';
						}
					}
				},
				{
					field: 'fanMaxSpeed',
					title: '风扇最大转速',
					align: 'center',
					editable: {
						type: 'text',
						validate: function(value) {
							value = $.trim(value);
							var ex = /^\d+$/;
							if (!ex.test(value) || value < 0 || value > 10000) {
								return '无效的风扇最大转速（0-10000）。';
							}
							return '';
						}
					}
				},
				{
					field: 'tempNum',
					title: '温感数',
					align: 'center',
					editable: {
						type: 'text',
						validate: function(value) {
							value = $.trim(value);
							var ex = /^\d+$/;
							if (!ex.test(value) || value < 0 || value > 100) {
								return '无效的温感数（0-100）。';
							}
							return '';
						}
					}
				},
				{
					field: 'tempMaxValue',
					title: '最高温度',
					align: 'center',
					editable: {
						type: 'text',
						validate: function(value) {
							value = $.trim(value);
							var ex = /^\d+$/;
							if (!ex.test(value) || value < 0 || value > 100) {
								return '无效的最高温度（0-100）。';
							}
							return '';
						}
					}
				},
				{
					field: 'chainMinNum',
					title: '最少工作链条数',
					align: 'center',
					sortable: true,
					editable: {
						type: 'text',
						validate: function(value) {
							value = $.trim(value);
							var ex = /^\d+$/;
							if (!ex.test(value) || value < 0 || value > 100) {
								return '无效的最少工作链条数（0-100）。';
							}
							return '';
						}
					}
				},
				{
					field: 'chipMinNum',
					title: '最少工作芯片数',
					align: 'center',
					editable: {
						type: 'text',
						validate: function(value) {
							value = $.trim(value);
							var ex = /^\d+$/;
							if (!ex.test(value) || value < 0 || value > 1000) {
								return '无效的最少工作芯片数（0-1000）。';
							}
							return '';
						}
					}
				},
				{
					field: 'operate',
					title: '操作',
					align: 'center',
					events: window.operateEvents = {
							'click .edit': function (e, value, row, index) {
								openEditDialog(row);
					        }/*,
					        'click .delete': function (e, value, row, index) {
					        	var rows = new Array(1);
					        	rows[0] = row;
					        	openRemoveDialog(rows);
					        }*/
					},
					formatter: function(value, row, index) {
						return [
								'<a class="edit" href="javascript:void(0)" title="修改">',
								'<i class="glyphicon glyphicon-edit"></i>',
								'</a>  '/*,
								'<a class="delete" href="javascript:void(0)" title="删除">',
								'<i class="glyphicon glyphicon-remove"></i>',
								'</a>'*/
						       ].join('');
					}
				}
			]
		});
	}
});